//
//  CNServiceInfo.m
//  CarNote
//
//  Created by linshili on 13-9-17.
//  Copyright (c) 2013年 linshili. All rights reserved.
//

#import "CNServiceInfo.h"

@implementation CNServiceInfo

+ (NSArray *)serviceConstraints
{
    static NSArray *gServiceConstraints = nil;
    static dispatch_once_t onceTokenServiceConstraints;
    dispatch_once(&onceTokenServiceConstraints, ^{
        gServiceConstraints = [NSArray arrayWithContentsOfFile:@"ServiceTypes.plist"];
    });
    
    return gServiceConstraints;
}

- (void)servicesFromJsonString:(NSString *)jsonString
{
    NSError *error = [[NSError alloc] init];
    
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    _services = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    if (_services == nil) {
        NSLog(@"%@", [error localizedDescription]);
    }
}


- (NSString *)jsonStringFromServices
{
    if (_services != nil) {
        NSError *error = [[NSError alloc] init];
        NSData *data = [NSJSONSerialization dataWithJSONObject:_services options:0 error:&error];
        if (data) {
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            return jsonString;
        }
    }

    return @"[]";
}

- (void)addService:(NSInteger)serviceTypeIndex
{
    if (_services == nil) {
        _services = [[NSMutableArray alloc] init];
    }
    
    NSDictionary *serviceData = [[CNServiceInfo serviceConstraints] objectAtIndex:serviceTypeIndex];
    [_services addObject:serviceData];
}


- (void)deleteService:(NSInteger)serviceTypeIndex
{
    if (_services) {
        NSDictionary *serviceContraintsItem = [[CNServiceInfo serviceConstraints] objectAtIndex:serviceTypeIndex];
        for (NSDictionary *serviceData in _services) {
            if ([[serviceData objectForKey:@"name"] isEqualToString:[serviceContraintsItem objectForKey:@"name"]]) {
                [_services removeObject:serviceData];
                return ;
            }
        }

    }
}

@end
